<?php

namespace app\api\controller;

use app\common\controller\Api;

/**
 * 示例接口
 */
class Cart extends Api
{


    protected $model = null;
    protected $noNeedRight = '*';

    public function _initialize()
    {
        $this->model = new \app\admin\model\Cart;
    }
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
   
   public function storage()
   {
       //设置过滤方法
       $this->request->filter(['strip_tags']);
       if ($this->request->isPost()) {
           $post = $this->request->post();
           $user_id = $this->auth->id;
           $return = '';
           // 清空购物车
           if($post['type'] == 'empty'){
               $this->model->where(['user_id' => $this->auth->id])->delete();
           // 新增购物车
           }else if($post['type'] == 'add'){
               $where = [
                   'product_id' => $post['product_id'],
                   'user_id' => $user_id
               ];
               // 查询是否已存在，如果已存在只改变数量和总价
               $cart = $this->model->where($where)->find();
               if($cart){
                   $num = $cart['num'] + 1;
                   $params = [
                       'num' => $num,
                       //1.0.5升级 'sum' => bcmul($cart['sku']['price'], $number)
                   ];
                   $cart->save($params);
               }else{
                   // 只新增ID，1.0.2升级
                   $where['num'] = 1;
                   $this->model->save($where, false);
               }
           // 新增购物车
           }else if($post['type'] == 'change'){
               $where = [
                   'product_id' => $post['product_id'],
                   'user_id' => $user_id
               ];
               $cart = $this->model->where($where)->find();
               // 1.0.5升级
               $cart->save(['num' => $post['num']]);
           // 批量删除
           }else if($post['type'] == 'del'){	
               foreach ($post['data'] as $row) {
                   $where = [
                       'product_id' => $row['product_id'],
                        'user_id' => $user_id,
                   ];
                   $this->model->where($where)->delete();
               }
           // 先将传来的批量写进关注表，在删除这些
           }else{
               $this->error(__('网络繁忙'));
           }
           $this->success('更新购物车完成！', $return);
       }
       $this->error(__('非正常请求'));
   }

}
